package com.gitee.fsmxm.thinking.in.spring.dependency.injection;

import com.gitee.fsmxm.thinking.in.spring.dependency.injection.annotation.UserGroup;
import com.gitee.fsmxm.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collection;

/**
 * @Qualifier 限定 注解方式 依赖注入 demo
 */
public class QualifierAnnotationDependencyInjectionDemo {

    @Autowired
    private User user;

    @Autowired
    @Qualifier("user")
    private User user2;

    @Autowired
    private Collection<User> users;

    @Autowired
    @Qualifier
    private Collection<User> qualifierUsers;

    @Autowired
    @UserGroup
    private Collection<User> groupedUsers;

    // 不写配置类，在当前类 @Bean 会注入有问题
    public static class Config {
        @Bean
        @Qualifier // 进行逻辑分组
        public User user7() {
            User user = new User();
            user.setId(7L);
            return user;
        }

        @Bean
        @Qualifier // 进行逻辑分组
        public User user8() {
            User user = new User();
            user.setId(8L);
            return user;
        }

        @Bean
        @UserGroup // 进行逻辑分组
        public User user9() {
            User user = new User();
            user.setId(9L);
            return user;
        }
    }

    public static void main(String[] args) {

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);

        beanDefinitionReader.loadBeanDefinitions("classpath:/META-INF/dependency-lookup-context.xml");

        applicationContext.register(QualifierAnnotationDependencyInjectionDemo.class, Config.class);

        applicationContext.refresh();

        QualifierAnnotationDependencyInjectionDemo demo = applicationContext.getBean(QualifierAnnotationDependencyInjectionDemo.class);

        System.out.println(demo.user);
        System.out.println(demo.user2);
        System.out.println(demo.users);
        System.out.println(demo.qualifierUsers);
        System.out.println(demo.groupedUsers);

    }

}
